/**
 * 公共JS函数
 * 动态管理
 * @author HuJun
 * @return commonJs
 * @type {function(): {getStatusBarHeight: function(): (number|string), logger: {enableDebug: boolean, debug: function(*, *=): void}}}
 */
export const commonJs = () => ({
	systemConfig: {
		requestUrl: 'https://api.skunld.net',
		params: {},
		groupInfo: {},
		shopIndex: null,
		userInfo: {},
		groupShopList: [],
		autoLogin: null,
		headerObj: {
			'X-Merchant-ID': null,
			'Authorization-Token': ''
		},
		whiteUrl: [
			'/group/bindGroup',
			'/group/groupLogin'
		],
		iconBackgroundColors: [
			"#ff6f3f", // 橙色
			"#4caf50", // 绿色
			"#2196f3", // 蓝色
			"#9c27b0", // 紫色
			"#ffeb3b", // 黄色
			"#00bcd4", // 青色
			"#e91e63", // 粉色
			"#3f51b5", // 深蓝色
			"#8bc34a", // 亮绿色
			"#f44336", // 红色
			"#607d8b", // 深灰色
			"#795548", // 咖啡色
			"#ffc107", // 亮黄色
			"#673ab7", // 深紫色
			"#009688", // 深青色
			"#ff5722", // 橘红色
			"#cddc39", // 黄绿色
			"#607d8b", // 石墨灰
			"#d32f2f", // 鲜红色
			"#1976d2", // 深蓝色
			"#388e3c", // 草绿色
			"#0288d1", // 碧蓝色
			"#8e24aa", // 薰衣草紫色
			"#fbc02d", // 橙黄色
			"#0288d1", // 亮蓝色
			"#7b1fa2", // 紫罗兰色
			"#512da8", // 紫色
			"#f57c00", // 深橙色
			"#c2185b", // 珊瑚红色
			"#0277bd", // 浅蓝色
			"#00897b", // 松石绿
			"#f44336", // 红色
			"#7b2cbf", // 深紫红色
			"#d32f2f", // 深红色
			"#81c784", // 明亮的绿色
			"#0097a7", // 深青色
			"#9c27b0", // 紫色
			"#f57f17", // 金色橙色
			"#536dfe", // 明亮的蓝色
			"#fb8c00", // 锈红色
			"#66bb6a" // 清新绿色
		]
	},

	// 缓存数据
	cacheData: {},

	/**
	 * 缓存来源
	 * 0 内存或者本地
	 * 1 内存
	 * 2 本地
	 */
	cacheFrom: [0, 1, 2],

	/**
	 * 初始化获取请求商户ID，集团为0
	 * @return {*}
	 */
	getRequestShopId: function() {
		try {
			if (this.systemConfig.groupInfo.hasOwnProperty('group_id') && this.systemConfig.groupInfo
				.group_id && this.systemConfig.groupInfo.group_id > 0) {
				return this.systemConfig.groupInfo.group_id
			}
			const groupInfo = uni.getStorageSync('groupInfo');
			if (groupInfo && groupInfo !== '' && groupInfo != undefined && typeof groupInfo == 'object' &&
				Object.keys(groupInfo).length > 0) {
				this.systemConfig.groupInfo = groupInfo
				return groupInfo.group_id
			}
			return 0
		} catch (e) {
			this.logger.debug(e, 'error')
		}
	},

	/**
	 * 格式化大小
	 * @param sizeInKB
	 * @returns {`${string} ${string}`}
	 */
	formatStorageSize: function(sizeInKB) {
		const units = ["KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
		let index = 0;
		let size = parseFloat(sizeInKB);

		// 如果数值过大，递归除以 1024 并递增单位
		while (size >= 1024 && index < units.length - 1) {
			size /= 1024;
			index++;
		}

		return `${size.toFixed(2)} ${units[index]}`;
	},

	/**
	 * 当前访问的商户索引
	 * @returns {*}
	 */
	getChooseShopIndex: function() {
		let index = 0
		if (this.systemConfig.shopIndex != null && this.systemConfig.shopIndex >= 0) {
			index = this.systemConfig.shopIndex
		} else {
			try {
				index = uni.getStorageSync('shopIndex')
				if (!index || index == null || index == undefined) {
					index = 0
				}
				const shopInfo = this.systemConfig.groupShopList[index]
				if (!shopInfo || shopInfo === undefined) {
					index = 0
				}
				this.systemConfig.shopIndex = index
			} catch (error) {
				index = 0
			}
		}
		return index
	},

	/**
	 * @return {{top: number, bottom: number, statusbarHeight: number}}
	 */
	getSafeAreaPadding: function() {
		let topHeight = 0;
		let result = {
			top: 0,
			bottom: 0,
			statusbarHeight: 0
		};
		let info = this.getSystemInfo();
		if (typeof info.screenHeight != 'undefined' && typeof info.safeArea == 'object' && typeof info
			.safeArea.top != 'undefined') {
			result.top = Number(info.screenTop) === 0 ? Number(info.safeArea.top) : 0;
		}
		if (typeof info.screenHeight != 'undefined' && typeof info.safeArea == 'object' && typeof info
			.safeArea.bottom != 'undefined') {
			result.bottom = Number(info.screenHeight - info.safeArea.bottom);
		}
		result.statusbarHeight = !isNaN(info.statusBarHeight) ? Number(info.statusBarHeight) : 0;
		return result;
	},

	/**
	 * 电话隐藏
	 * @param phoneNumber
	 * @return {*}
	 */
	hidePhoneNumber: function(phoneNumber) {
		return phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
	},

	formatNumber: function(money) {
		// 判断是否为整数（即小数部分是否为 0）
		if (money % 1 === 0) {
			return Number(money).toString()
		} else {
			return Number(money).toFixed(2)
		}
	},

	/**
	 * @param target
	 * @return {{}|*|*[]}
	 */
	clone: function(target) {
		let buf
		if (target instanceof Array) {
			buf = [];
			let i = target.length
			while (i--) {
				buf[i] = this.clone(target[i]);
			}
			return buf;
		} else if (target instanceof Object) {
			buf = {};
			for (const k in target) {
				buf[k] = this.clone(target[k]);
			}
			return buf;
		} else {
			return target;
		}
	},

	/**
	 * @return {null}
	 */
	getSystemInfo: function() {
		if (typeof this.systemInfo == 'undefined' || this.systemInfo == null) {
			this.systemInfo = uni.getSystemInfoSync();
		}
		return this.systemInfo;
	},

	/**
	 * 获取集团信息
	 * @returns {{}}
	 */
	getGroupInfo: function() {
		let groupInfo = null
		if (this.systemConfig.groupInfo && Object.keys(this.systemConfig.groupInfo).length > 0) {
			groupInfo = this.systemConfig.groupInfo
		} else {
			try {
				groupInfo = uni.getStorageSync('groupInfo')
				if (!groupInfo || groupInfo == '' || groupInfo == undefined) {
					// this.hrefBind()
					return groupInfo = null
				}
				this.systemConfig.groupInfo = groupInfo
			} catch (error) {
				groupInfo = null
				//TODO handle the exception
			}
		}
		return groupInfo
	},

	/**
	 * 获取集团商户列表
	 * @returns {*}
	 */
	getShopList: function() {
		let shopList = null
		if (this.systemConfig.groupShopList && this.systemConfig.groupShopList.length > 0) {
			shopList = this.systemConfig.groupShopList
		} else {
			try {
				shopList = JSON.parse(uni.getStorageSync('groupShopList'))
				this.systemConfig.groupShopList = shopList
			} catch (error) {
				shopList = null
				//TODO handle the exception
			}
		}
		return shopList
	},

	/**
	 * 获取缓存大小
	 * @returns {{size: string, limit: string}}
	 */
	getStorageSize: function() {
		try {
			const res = uni.getStorageInfoSync();
			return {
				size: res.currentSize + 'KB',
				limit: this.formatStorageSize(res.limitSize)
			}
		} catch (e) {
			// error
			return {
				size: '0KB',
				limit: '0KB'
			}
		}
	},

	/**
	 * 获取登录用户信息
	 * @function getUserInfo()
	 * @returns {{}}
	 */
	getUserInfo: function() {
		let userInfo = {}
		if (this.systemConfig.userInfo && Object.keys(this.systemConfig.userInfo).length > 0) {
			userInfo = this.systemConfig.userInfo
		} else {
			try {
				userInfo = uni.getStorageSync('userInfo')
				if (!userInfo || userInfo == undefined || userInfo == null) {
					userInfo = {}
				} else {
					this.systemConfig.userInfo = userInfo
				}
			} catch (error) {
				userInfo = {}
				//TODO handle the exception
			}
		}
		return userInfo
	},

	/**
	 * @function queryCache
	 * @param url 请求地址
	 * @param params 请求参数
	 * @param callbacks 回调参数
	 * @param cacheKey 缓存key
	 * @param header 请求头部
	 * @param cacheTime 缓存时间
	 * @param cacheFrom 缓存状态  0 内存或者本地  1 内存 2 本地
	 * @param method 请求方式 get post
	 */
	queryCache: function(url, params = {}, callbacks, header = {}, cacheKey = '', cacheTime = 0, cacheFrom = 0,
		method = 'POST') {
		if (cacheKey !== '' && cacheKey !== undefined && cacheKey.length > 0) {
			try {
				let cachedData = null
				// 变量中取缓存
				if (cacheFrom === 0 || cacheFrom === 1) {
					if (this.cacheData.hasOwnProperty(cacheKey) && this.cacheData[cacheKey] !== '' && this
						.cacheData[cacheKey] !== undefined) {
						cachedData = this.cacheData[cacheKey];
					}
				}
				// 本地缓存中获取
				if (!cachedData && (cacheFrom === 0 || cacheFrom === 2)) {
					const localData = uni.getStorageSync(cacheKey);
					if (localData && localData.expireTime > Date.now()) {
						cachedData = localData.data;
					}
				}
				// 缓存存在，直接返回数据
				if (cachedData) {
					if (typeof callbacks.success === 'function') {
						callbacks.success(cachedData)
						return
					}
				}
			} catch (e) {
				this.logger.debug(e, 'error')
			}
		}
		// 缓存不存在，发送请求
		this.sendRequest(url, params, method, header, {
			before: callbacks.before,
			success: (data) => {
				if ((cacheFrom === 0 || cacheFrom === 1) && cacheKey && cacheKey.length > 0) {
					this.cacheData[cacheKey] = data;
				}
				if ((cacheFrom === 0 || cacheFrom === 2) && cacheKey && cacheKey.length > 0 &&
					cacheTime > 0) {
					const expireTime = cacheTime > 0 ? Date.now() + cacheTime * 1000 :
						0;
					uni.setStorageSync(cacheKey, {
						data,
						expireTime
					});
				}
				if (typeof callbacks.success === 'function') {
					callbacks.success(data);
				}
			},
			fail: (err) => {
				callbacks.fail(err)
			},
			complete: callbacks.complete
		});
	},

	/**
	 * 显示加载框
	 * @param message
	 * @param mask
	 */
	showLoading: function(message = '加载中', mask = false) {
		uni.showLoading({
			title: message,
			mask
		})
	},

	/**
	 * 关闭加载框
	 * @param time
	 */
	hideLoading: function(time = 300) {
		setTimeout(() => {
			uni.hideLoading()
		}, time)
	},

	/**
	 * 封装 uni.request
	 * @param {string} url 请求地址
	 * @param {Object} params 请求参数
	 * @param {string} method 请求方法 (GET, POST 等)
	 * @param {Object} header 请求头部
	 * @param {Object} callbacks 回调函数集合 (before, success, fail, complete)
	 */
	sendRequest: function(url, params = {}, method = 'GET', header = {}, callbacks = {}) {
		const {
			before,
			success,
			fail,
			complete
		} = callbacks;
		const self = this
		let merchantId = 0
		if (Object.keys(header).length > 0) {
			this.systemConfig.headerObj = Object.assign(this.systemConfig.headerObj, header)
			if (header.hasOwnProperty('X-Merchant-ID')) {
				merchantId = header['X-Merchant-ID']
			}
		}
		// 不存在请求商户ID 跳转至绑定页
		if (!this.systemConfig.headerObj["X-Merchant-ID"] && url !== '/group/bindGroup') {
			merchantId = this.getRequestShopId()
			if (!merchantId || merchantId === 0 || merchantId === undefined) {
				// this.showMessage('未找到商户信息！')
				this.hrefBind()
				return
			}
			this.systemConfig.headerObj["X-Merchant-ID"] = merchantId
		}

		if (url === '/group/bindGroup') {
			this.systemConfig.headerObj["X-Merchant-ID"] = 0
		}

		// 不存在token 且不是白名单下 跳转至登录页
		if (!this.systemConfig.headerObj["Authorization-Token"] && !this.systemConfig.whiteUrl.includes(
				url) && merchantId) {
			try {
				let user = this.getUserInfo()
				if (!user || Object.keys(user).length <= 0 || !user.hasOwnProperty('token')) {
					// this.showMessage('未找到登录令牌！')
					this.hrefLogin()
					return
				} else {
					const token = user.token.token
					if (!token || token === '' || token === undefined) {
						// this.showMessage('未找到登录令牌！')
						this.hrefLogin()
						return
					} else {
						self.systemConfig.headerObj['Authorization-Token'] = token
					}
				}
			} catch (e) {
				// this.showMessage('登录令牌异常！')
				this.hrefLogin()
				return
			}
		}

		// 执行 before 回调
		if (typeof before === 'function') {
			before();
		}
		uni.request({
			url: self.systemConfig.requestUrl + url,
			method: method || 'GET',
			data: params,
			header: self.systemConfig.headerObj,
			success: (res) => {
				if (res.hasOwnProperty('data') && res['data'].hasOwnProperty('code') && res
					.statusCode === 200 && res.data.code === 200 && typeof success ===
					'function') {
					success(res.data)
				} else if (typeof fail === 'function') {
					if (res.hasOwnProperty('data') && res['data'].hasOwnProperty('code')) {
						if (res.data.code === 401 && !this.systemConfig.whiteUrl.includes(
								url)) {
							// 判断是否自动登录状态
							if (self.getAutoLoginStatus() == 1) {
								self.autoLoginStaff(url, params, header, callbacks)
								return
							} else {
								self.hrefLogin()
							}
						} else if (res.data.code === 204 && !this.systemConfig.whiteUrl
							.includes(url)) {
							// 判断是否自动登录状态
							if (self.getAutoLoginStatus() == 1) {
								self.autoLoginStaff(url, params, header, callbacks)
								return
							} else {
								self.hrefLogin()
							}
						} else if (res.data.code === 205 && !this.systemConfig.whiteUrl
							.includes(url)) {
							// 判断是否自动登录状态
							if (self.getAutoLoginStatus() == 1) {
								self.autoLoginStaff(url, params, header, callbacks)
								return
							} else {
								self.hrefLogin()
							}
						} else if (res.data.code === 201) {
							self.showMessage(res.data.msg)
						} else {
							self.showMessage('请求错误!')
						}
						return
					}
					fail(res)
				}
			},
			fail: (err) => {
				uni.getNetworkType({
					complete: res => {
						let networkType = res.networkType || 'none';
						if (networkType === 'none') {
							self.showMessage('当前无网络,请检查您的网络连接')
						} else if (err.errMsg === 'request:fail timeout') {
							self.showMessage('网络连接超时')
						} else if (err.errMsg !== 'request:fail') {
							self.showMessage(`错误原因：${err.errMsg}`)
						} else {
							self.showMessage(`未知错误`)
						}
					}
				});
				if (typeof fail === 'function') {
					fail(err)
				}
			},
			complete: () => {
				if (typeof complete === 'function') {
					complete()
				}
			}
		});
	},

	// 员工自动登录操作
	autoLoginStaff: function(url, paramsReq, header, callbacks) {
		const self = this
		const user = self.getUserInfo()
		if (!user || Object.keys(user).length <= 0 || user == null || user == undefined) {
			self.hrefLogin()
			return
		}
		const params = {
			name: user.user_name,
			password: user.user_password,
			group_id: self.getRequestShopId()
		}
		self.queryCache('/group/groupLogin', params, {
			before() {
				uni.showLoading({
					title: '自动登录中'
				})
			},
			success(res) {
				try {
					const {
						code,
						data,
						msg,
						server_ip
					} = res
					self.systemConfig.userInfo = data
					self.systemConfig.headerObj['Authorization-Token'] = data.token.token
					self.setStorage(
						'userInfo',
						data,
						function() {
							self.queryCache(url, paramsReq, callbacks, header, )
						}
					)
				} catch (error) {
					self.showMessage(error)
				}
			},
			fail(err) {
				self.logger.debug(err, 'error')
			},
			complete() {
				setTimeout(() => {
					uni.hideLoading()
				}, 1500)
			}
		})
	},

	/**
	 * 跳转登录
	 */
	hrefLogin: function() {
		uni.reLaunch({
			url: '/pages/login'
		})
	},

	/**
	 * 跳转绑定
	 */
	hrefBind: function() {
		uni.reLaunch({
			url: '/pages/bind'
		})
	},

	/**
	 * 消息提示
	 * @param message
	 * @param icon
	 * @param time
	 * @param mask
	 */
	showMessage: function(message, icon = 'none', time = 2000, mask = false) {
		uni.showToast({
			title: message,
			icon: icon,
			duration: time,
			mask: mask
		})
	},

	/**
	 * @description logger
	 * 调试模式 enableDebug 是否开启
	 * @function debug 打印内容以及结果
	 */
	logger: {
		enableDebug: false,
		debug: function(message, level = 'info') {
			if (this.enableDebug) {
				switch (level) {
					case 'info':
						console.info(message)
						break
					case 'log':
						console.log(message)
						break
					case 'warn':
						console.warn(message)
						break
					case 'error':
						console.error(message)
						break
					case 'debug':
						console.debug(message)
						break
					default:
						console.log(message)
				}
			}
		}
	},

	/**
	 * @function getStatusBarHeight
	 * 获取状态栏高度
	 * @return number|string
	 */
	getStatusBarHeight: function() {
		uni.getSystemInfo({
			success: (res) => {
				this.logger.debug('状态高度：' + res)
				return res
			},
			fail: (err) => {
				this.logger.debug('状态高度：' + err)
			},
			complete: function() {

			}
		})
	},

	// 获取用户是否自动登录账户
	getAutoLoginStatus: function() {
		let autoLoginStatus = this.systemConfig.autoLogin
		if (autoLoginStatus == '' || autoLoginStatus == undefined || autoLoginStatus == null) {
			autoLoginStatus = uni.getStorageSync('autoLogin')
			if (autoLoginStatus == null || autoLoginStatus == undefined || autoLoginStatus == '') {
				autoLoginStatus = 1
				uni.setStorageSync('autoLogin', autoLoginStatus)
				this.systemConfig.autoLogin = autoLoginStatus
			} else {
				this.systemConfig.autoLogin = autoLoginStatus
			}
		}
		return autoLoginStatus
	},

	/**
	 * 同步设置缓存
	 * @param key
	 * @param data
	 */
	setStorageSync: function(key, data) {
		if (key && data) {
			uni.setStorageSync(key, data)
		} else {
			this.showMessage('同步缓存数据失败！')
		}
	},

	/**
	 * 异步设置缓存
	 * @param key
	 * @param data
	 * @param callback
	 */
	setStorage: function(key, data, callback) {
		if (key !== '' && data !== '') {
			uni.setStorage({
				key,
				data,
				success: function() {
					if (callback && typeof callback === 'function') {
						callback()
					}
				}
			})
		} else {
			this.showMessage('异步缓存数据失败！')
		}
	},

	/**
	 * 异步删除缓存
	 * @param key
	 * @param callback
	 */
	clearStorage: function(key, callback) {
		uni.removeStorage({
			key: key,
			success: function(res) {
				if (callback && typeof callback === 'function') {
					callback('success')
				}
			}
		})
	},

	/**
	 * 同步删除缓存
	 * @param key
	 */
	clearStorageSync: function(key) {
		try {
			uni.removeStorageSync(key);
		} catch (e) {
			// error
		}
	},

	/**
	 * 同步获取系统应用信息
	 * @returns {*}
	 */
	getSystemInfoSync: function() {
		const systemInfo = uni.getSystemInfoSync();
		return systemInfo
	},

	/**
	 * 获取背景颜色
	 * @param index
	 * @return {string}
	 */
	getRandomColor: function(index = null) {
		if (!index) {
			const randomIndex = Math.floor(Math.random() * this.systemConfig.iconBackgroundColors.length);
			return this.systemConfig.iconBackgroundColors[randomIndex]
		}
		return this.systemConfig.iconBackgroundColors[index]
	},

})